package com.jh.paymentchannel.service;

import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.TokenUtil;
import com.jh.paymentchannel.business.BankCard4AuthBusiness;
import com.jh.paymentchannel.business.BankCardImgBusiness;
import com.jh.paymentchannel.util.Util;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.HashMap;

@Controller
@EnableAutoConfiguration
public class BankCardImgService {

    @Autowired
    private BankCardImgBusiness bankCardImgBusiness;

    @Autowired
    private BankCard4AuthBusiness bankCard4AuthBusiness;
    @Autowired
    Util util;



    /**
     * 银行卡图片识别
     *
     * @param request
     * @param img
     * @param token
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/bankcard/img/{token}")
    @ResponseBody
    public Object bradcardImg(HttpServletRequest request,
                              @RequestParam("img") String img,
                              @PathVariable("token") String token) {
        HashMap<Object, Object> map = new HashMap<>();
        if (img == null || "".equals(img)) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "您输入的信息有误，请重新输入");
            return map;
        }
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
            map.put(CommonConstants.RESP_MESSAGE, "token无效");
            return map;
        }

        //调用user查询用户是否实名认证
        RestTemplate restTemplate = new RestTemplate();
        URI url = util.getServiceUrl("user", "error url request");
        String uri = url.toString() + "/v1.0/user/bank/auth";
        MultiValueMap<Object, Object> multimap = new LinkedMultiValueMap<>();
        multimap.add("userId", userId);
        String result = restTemplate.postForObject(uri, multimap, String.class);
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONObject jsonObject1 = jsonObject.getJSONObject("result");
        //限制调用次数


        //实名认证成功
        if (jsonObject.getString("resp_code") != null && CommonConstants.SUCCESS.equals(jsonObject.getString("resp_code"))) {
            map.put("results", bankCardImgBusiness.bankCardImgAuth(img, userId));
            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESP_MESSAGE, "接口返回成功");
        } else {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "绑卡失败,请先进行实名认证");
        }
        return map;
    }


   /* public static void main(String[] args) {
        String host = "https://bankocr.market.alicloudapi.com";
        String path = "/cardbank";
        String method = "POST";
        String appcode = "efd428002d8f416ea8a6adec212f9b43";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        String strImg = getImageStr("C:/123/3.jpg");
        strImg = "data:image/jpeg;base64," + strImg;
        System.out.println(strImg);
        bodys.put("img", strImg);
        //或者base64
        //bodys.put("img", "data:image/jpeg;base64......");
        try {
            *//**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             *//*
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            //System.out.println(response.toString());
            //获取response的body
            String res = EntityUtils.toString(response.getEntity());
            System.out.println(res);
            JSONObject jsonObject = JSONObject.fromObject(res);
            String msg = jsonObject.getString("code");
            System.out.println(msg);
            String result = jsonObject.getString("result");
            JSONObject jsonObject1 = JSONObject.fromObject(result);
            System.out.println(jsonObject1.get("bank_card_number"));


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    *//**
     * @return
     * @Description: 根据图片地址转换为base64编码字符串
     * @Author:
     * @CreateTime:
     *//*
    public static String getImageStr(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }*/


}
